package com.ww.sound_emission.controller;



import cn.hutool.core.io.resource.InputStreamResource;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ww.sound_emission.domain.MinioUploads;
import com.ww.sound_emission.service.MinioUploadsService;
import io.minio.*;
import io.minio.errors.MinioException;
import io.minio.messages.Bucket;


import io.minio.messages.Item;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.InputStream;
import java.util.*;

@RequestMapping("/down")
@RestController
@CrossOrigin
public class FileDownloadController {

    @Autowired
    private MinioClient minioClient;

    @Value("${minio.bucket-name}")
    private String bucketName;


    @GetMapping("/downloadS")
    public ResponseEntity<InputStreamResource> downloadFile(@RequestParam String fileName) {
        try {
            // 从 MinIO 获取文件
            InputStream inputStream = minioClient.getObject(
                    GetObjectArgs.builder()
                            .bucket(bucketName)
                            .object(fileName)
                            .build()
            );

            // 设置响应头
            HttpHeaders headers = new HttpHeaders();
            headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + fileName);
            headers.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_OCTET_STREAM_VALUE);

            return ResponseEntity.ok()
                    .headers(headers)
                    .body(new InputStreamResource(inputStream));
        } catch (MinioException e) {
            e.printStackTrace();
            return ResponseEntity.status(500).body(null);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(500).body(null);
        }



    }






    // @GetMapping("/buckets")
    // public Map<String, Object> listBucketsAndFiles() {
    //     Map<String, Object> result = new HashMap<>();
    //     try {
    //         // 获取所有存储桶
    //         List<Bucket> buckets = minioClient.listBuckets();
    //         result.put("status", "success");
    //         result.put("message", "成功获取存储桶信息");
    //
    //         // 遍历每个存储桶，获取文件信息
    //         List<Map<String, Object>> bucketList = new ArrayList<>();
    //         for (Bucket bucket : buckets) {
    //             Map<String, Object> bucketInfo = new HashMap<>();
    //             bucketInfo.put("bucketName", bucket.name());
    //             bucketInfo.put("creationDate", bucket.creationDate().toString());
    //
    //             // 获取存储桶中的文件列表
    //             List<Map<String, String>> fileList = new ArrayList<>();
    //             Iterable<Result<Item>> objects = minioClient.listObjects(
    //                     ListObjectsArgs.builder()
    //                             .bucket(bucket.name())
    //                             .recursive(true)
    //                             .build()
    //             );
    //
    //             for (Result<Item> itemResult : objects) {
    //                 Item item = itemResult.get();
    //                 if (!item.isDir()) { // 忽略文件夹
    //                     Map<String, String> fileInfo = new HashMap<>();
    //                     fileInfo.put("fileName", item.objectName());
    //                     // fileInfo.put("fileType", item.contentType());
    //                     fileList.add(fileInfo);
    //                 }
    //             }
    //
    //             bucketInfo.put("files", fileList);
    //             bucketList.add(bucketInfo);
    //         }
    //
    //         result.put("buckets", bucketList);
    //     } catch (MinioException e) {
    //         result.put("status", "error");
    //         result.put("message", "获取存储桶信息失败: " + e.getMessage());
    //     } catch (Exception e) {
    //         result.put("status", "error");
    //         result.put("message", "发生未知错误: " + e.getMessage());
    //     }
    //     return result;
    // }









    @Autowired
    private MinioUploadsService minioUploadsService; // MyBatis Plus 的 Service

    @GetMapping("/buckets")
    public Map<String, Object> listBucketsAndFiles() {
        Map<String, Object> result = new HashMap<>();
        try {
            // 清空 minio_uploads 表中的数据
            minioUploadsService.remove(new QueryWrapper<>());

            // 获取所有存储桶
            List<Bucket> buckets = minioClient.listBuckets();
            result.put("status", "success");
            result.put("message", "成功获取存储桶信息");

            // 遍历每个存储桶，获取文件信息
            List<Map<String, Object>> bucketList = new ArrayList<>();
            for (Bucket bucket : buckets) {
                Map<String, Object> bucketInfo = new HashMap<>();
                bucketInfo.put("bucketName", bucket.name());
                bucketInfo.put("creationDate", bucket.creationDate().toString());

                // 获取存储桶中的文件列表
                List<Map<String, String>> fileList = new ArrayList<>();
                Iterable<Result<Item>> objects = minioClient.listObjects(
                        ListObjectsArgs.builder()
                                .bucket(bucket.name())
                                .recursive(true)
                                .build()
                );

                for (Result<Item> itemResult : objects) {
                    Item item = itemResult.get();
                    if (!item.isDir()) { // 忽略文件夹
                        Map<String, String> fileInfo = new HashMap<>();
                        fileInfo.put("fileName", item.objectName());
                        // fileInfo.put("fileType", item.contentType());
                        fileList.add(fileInfo);

                        // 将文件信息插入到 minio_uploads 表中
                        MinioUploads minioUploads = new MinioUploads();
                        minioUploads.setFileName(item.objectName());
                        // minioUploads.setFileSize(item.objectSize());
                        minioUploads.setBucketName(bucket.name());
                        minioUploads.setObjectPath(bucket.name() + "/" + item.objectName());
                        minioUploads.setUploadTime(new Date());
                        minioUploads.setUploadUser("admin"); // 假设上传用户是 admin
                        // minioUploads.setFileType(item.contentType());
                        minioUploads.setEtag(item.etag());
                        minioUploads.setIsPublic(0); // 假设文件默认是私有的
                        minioUploads.setMetadata(null); // 元数据可以为空或自定义

                        minioUploadsService.save(minioUploads); // 保存到数据库
                    }
                }

                bucketInfo.put("files", fileList);
                bucketList.add(bucketInfo);
            }

            result.put("buckets", bucketList);
        } catch (MinioException e) {
            result.put("status", "error");
            result.put("message", "获取存储桶信息失败: " + e.getMessage());
        } catch (Exception e) {
            result.put("status", "error");
            result.put("message", "发生未知错误: " + e.getMessage());
        }
        return result;
    }













}